package cn.wjx.taobaounion.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import cn.wjx.taobaounion.R;
import cn.wjx.taobaounion.utils.LogUtils;

/**
 * @author WuChangJian
 * @date 2020/6/22 16:15
 */
public class AutoLooperViewpager extends ViewPager {

    private boolean mIsLooper = true;
    private static final long DEFAULT_DURATION = 3000;
    private long mDuration = DEFAULT_DURATION;

    public AutoLooperViewpager(@NonNull Context context) {
        this(context, null);
    }

    public AutoLooperViewpager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public void init(Context context, AttributeSet attrs) {
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.AutoLooperViewpager);
        mDuration = t.getInteger(R.styleable.AutoLooperViewpager_duration, (int) DEFAULT_DURATION);
        LogUtils.d(this, "duration -->" + mDuration);
        t.recycle();
    }

    public void setDuration(long duration) {
        mDuration = duration;
    }

    private Runnable mTask = new Runnable() {
        @Override
        public void run() {
            if (mIsLooper) {
                int currentItem = getCurrentItem();
                currentItem++;
                setCurrentItem(currentItem);
                postDelayed(this,mDuration);
            }
        }
    };

    public void startLooper() {
        post(mTask);
    }


    public void stopLooper() {
        mIsLooper = false;
    }

}
